import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { UserResponseData } from '@/types/response';

interface UserState {
  user: UserResponseData | null;
}

interface UserActions {
  setUser: (user: UserResponseData | null) => void;
  clearUser: () => void;
  updateUser: (updates: Partial<UserResponseData>) => void;
}

export const useUserStore = create<UserState & UserActions>()(
  persist(
    (set, get) => ({
      // 状态
      user: null,

      // 操作
      setUser: (user) => {
        set({
          user,
        });
      },

      clearUser: () => {
        set({
          user: null,
        });
      },

      updateUser: (updates) => {
        const { user } = get();
        if (user) {
          set({
            user: {
              ...user,
              ...updates,
            },
          });
        }
      },
    }),
    {
      name: 'user-storage', // localStorage 中的 key
      partialize: (state) => ({
        user: state.user,
      }),
    }
  )
);

